package no.ntnu.fp.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Locale;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MonthChooser extends JPanel implements ItemListener {
	
	private static final long serialVersionUID = 1L;
	//protected boolean hasSpinner;
	private JComboBox comboBox;
	private Locale locale;
	private int month;
    private DayChooser daychooser;
	
	public MonthChooser() {
		super();
		setName("JMonthChooser");
		setLayout(new BorderLayout());
		comboBox = new JComboBox();
		comboBox.addItemListener(this);
		comboBox.setPreferredSize(new Dimension(100, 30));
		locale = Locale.getDefault();
		monthNames();
		add(comboBox);
		setMonth(Calendar.getInstance().get(Calendar.MONTH));
	}
	
	public void monthNames() {
		DateFormatSymbols monthname = new DateFormatSymbols(locale);
		String[] months = monthname.getMonths();
		if (comboBox.getItemCount() == 12) {
			comboBox.removeAllItems();
		}
		for (int i = 0 ; i < 12 ; i++) {
			comboBox.addItem(months[i]);
		}
		comboBox.setSelectedIndex(month);
	}

	private void setMonth(int newMonth,boolean selected) {
		int oldMonth = month;
		month = newMonth;
		if (selected) {
			comboBox.setSelectedIndex(month);
		}
		if (daychooser != null) {
//			System.out.println("call the DayChooser Class");
			daychooser.setMonth(month);
		}
		// miss the day fireproperty
		firePropertyChange("month", oldMonth, month);
	}

	public void setDaychooser(DayChooser daychooser) {
		this.daychooser = daychooser;
	}

	public void itemStateChanged(ItemEvent arg0) {
		if (arg0.getStateChange() == ItemEvent.SELECTED) {
			int index = comboBox.getSelectedIndex();
			//System.out.println("Month is changed" + index);
			if ((index >= 0) && (index != month)) {
				setMonth(index,false);
			}
		}
	}
	public int getMonth() {
		return month;
	}

	public void setMonth(int newMonth) {
		if (newMonth < 0 || newMonth == Integer.MIN_VALUE) {
			setMonth(0, true);
		} else if (newMonth > 11) {
			setMonth(11, true);
		} else {
			setMonth(newMonth, true);
		}
	}

	
	public static void main(String args[]){
		JFrame  jfram = new JFrame();
		MonthChooser mc = new MonthChooser();
		jfram.add(mc);
		jfram.pack();
		jfram.setVisible(true);
		//System.out.println(mc.month);
	}
}
